/*
 * @Author: wxinlong 3075748076@qq.com
 * @Date: 2023-06-17 10:27:48
 * @LastEditors: wxinlong 3075748076@qq.com
 * @LastEditTime: 2023-06-17 11:30:15
 * @Description: 文件处理中间件
 * Copyright (c) 2023 by wxinlong 3075748076@qq.com, All Rights Reserved.
 */
const multer = require('multer')
const fs = require('fs')
const path = require('path')

// 文件上传配置
const storage = multer.diskStorage({
  // 上传的目标地址，这里我们就上传到本地根目录的 tempFiles 目录
  destination: (req, file, cb) => {
    const tempFolderPath = path.join(__dirname, '../tempFiles')
    // 如果目录不存在则创建
    if (!fs.existsSync(tempFolderPath)) {
      fs.mkdirSync(tempFolderPath)
    }
    cb(null, tempFolderPath)
  },
  // 定义上传的文件名
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname)
    const filename = `${Date.now()}_${Math.floor(Math.random() * 10000)}${ext}`
    cb(null, filename)
  }
})

// 文件上传中间件
const upload = multer({ storage })
const uploadMiddleware = upload.single('file')

module.exports = uploadMiddleware
